package com.zzyl.nursing.service.impl;

import java.util.Date;
import java.util.List;

import cn.hutool.core.util.IdcardUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSON;
import com.zzyl.common.ai.AIModelInvoker;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.common.utils.ollama.AIHealthReportAnalyzer;
import com.zzyl.nursing.dto.HealthAssessmentDto;
import com.zzyl.nursing.vo.HealthReportVo;
import com.zzyl.nursing.vo.SystemScore;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.HealthAssessmentMapper;
import com.zzyl.nursing.domain.HealthAssessment;
import com.zzyl.nursing.service.IHealthAssessmentService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;

/**
 * 健康评估Service业务层处理
 *
 * @author zhangyan
 * @date 2025-05-27
 */
@Service
public class HealthAssessmentServiceImpl extends ServiceImpl<HealthAssessmentMapper, HealthAssessment> implements IHealthAssessmentService {
    @Autowired
    private HealthAssessmentMapper healthAssessmentMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Autowired
    private AIHealthReportAnalyzer aiHealthReportAnalyzer;

    @Autowired
    private AIModelInvoker aiModelInvoker;

    /**
     * 查询健康评估
     *
     * @param id 健康评估主键
     * @return 健康评估
     */
    @Override
    public HealthAssessment selectHealthAssessmentById(Long id) {
        return getById(id);
    }

    /**
     * 查询健康评估列表
     *
     * @param healthAssessment 健康评估
     * @return 健康评估
     */
    @Override
    public List<HealthAssessment> selectHealthAssessmentList(HealthAssessment healthAssessment) {
        return healthAssessmentMapper.selectHealthAssessmentList(healthAssessment);
    }

    /**
     * 新增健康评估
     *
     * @param dto 健康评估
     * @return 结果
     */
    @Override
    public Long insertHealthAssessment(HealthAssessmentDto dto) {
        String idCard = dto.getIdCard();

        //redis 取出分析的pdf信息
        String content = (String) redisTemplate.boundHashOps("healthReport").get(idCard);
//            log.debug(content);
        String str;
        //本地ai
        try {
            str = aiHealthReportAnalyzer.analyzeHealthReport(content);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
        //百度ai
//        str = aiHealthReportAnalyzer.buildPrompt(content);
//        str = aiModelInvoker.qianfanInvoker(str);
//        str = aiHealthReportAnalyzer.extractJson(str);
        System.out.println(str);
        HealthReportVo healthReportVo = JSONUtil.toBean(str, HealthReportVo.class);
        log.debug(healthReportVo.toString());
        HealthAssessment healthAssessment = new HealthAssessment();
        healthAssessment.setElderName(dto.getElderName());
        healthAssessment.setIdCard(dto.getIdCard());
        healthAssessment.setBirthDate(IdcardUtil.getBirthDate(dto.getIdCard()).toLocalDateTime());
        healthAssessment.setAge(IdcardUtil.getAgeByIdCard(dto.getIdCard()));
        healthAssessment.setGender(IdcardUtil.getGenderByIdCard(dto.getIdCard()));
        double healthIndex = healthReportVo.getHealthAssessment().getHealthIndex();
        healthAssessment.setHealthScore(String.valueOf(healthIndex)); //健康评分
        healthAssessment.setRiskLevel(healthReportVo.getHealthAssessment().getRiskLevel()); //严重危险(健康, 提示, 风险, 危险, 严重危险)
        healthAssessment.setSuggestionForAdmission(healthIndex > 60 ? 0 : 1); //是否建议入住(0:建议，1:不建议)
        healthAssessment.setNursingLevelName(calculateTheScore(healthIndex)); //推荐护理等级
        healthAssessment.setAdmissionStatus(1); //入住情况(0:已入住，1:未入住)
        healthAssessment.setTotalCheckDate(healthReportVo.getTotalCheckDate()); //总检日期
        healthAssessment.setPhysicalExamInstitution(dto.getPhysicalExamInstitution()); //体检机构
        healthAssessment.setPhysicalReportUrl(dto.getPhysicalReportUrl()); //体检报告URL链接
        healthAssessment.setAssessmentTime(new Date()); //评估时间
        healthAssessment.setReportSummary(healthReportVo.getSummarize());  //报告总结
        String abnormalData = JSON.toJSONString(healthReportVo.getAbnormalData());
        healthAssessment.setAbnormalAnalysis(abnormalData); //异常分析
        //健康系统分值  (AI)
        healthAssessment.setSystemScore(JSONUtil.toJsonStr(healthReportVo.getSystemScore()));

        healthAssessmentMapper.insert(healthAssessment);
        return healthAssessment.getId();

    }

    private String calculateTheScore(double healthScore) {
        //处理边界
        if (healthScore < 0 || healthScore > 100) {
            throw new IllegalArgumentException("健康评分必须在0到100之间");
        }

        if (healthScore >= 60 && healthScore < 70) {
            return "三级护理等级";
        } else if (healthScore >= 70 && healthScore < 80) {
            return "二级护理等级";
        } else if (healthScore >= 80 && healthScore < 90) {
            return "一级护理等级";
        } else if (healthScore >= 90) {
            return "特级护理等级";
        }
        return "无";
    }

    /**
     * 修改健康评估
     *
     * @param healthAssessment 健康评估
     * @return 结果
     */
    @Override
    public int updateHealthAssessment(HealthAssessment healthAssessment) {
        return updateById(healthAssessment) ? 1 : 0;
    }

    /**
     * 批量删除健康评估
     *
     * @param ids 需要删除的健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除健康评估信息
     *
     * @param id 健康评估主键
     * @return 结果
     */
    @Override
    public int deleteHealthAssessmentById(Long id) {
        return removeById(id) ? 1 : 0;
    }

}
